﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ERP.ERPModels.HumanResources.MasterData;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Domain.Repositories;
using ERP.HumanResources.HumanResourceManagement.Dtos;

namespace ERP.Web.Controllers
{
    public class TalentRegistrationController : Controller
    {
        private readonly IRepository<TalentRegistration, int> _talentRegistrationRepository;

        public TalentRegistrationController(IRepository<TalentRegistration, int> talentRegistrationRepository)
        {
            _talentRegistrationRepository = talentRegistrationRepository;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取人才登记分页列表
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>分页数据</returns>
        [HttpPost]
        public async Task<JsonResult> GetTalentRegistrationList(GetTalentRegistrationDTO dto)
        {
            // 创建查询
            var query = await _talentRegistrationRepository.GetQueryableAsync();

            // 应用筛选条件
            if (!string.IsNullOrWhiteSpace(dto.EmployeeCode))
            {
                query = query.Where(x => x.EmployeeCode.Contains(dto.EmployeeCode));
            }

            if (!string.IsNullOrWhiteSpace(dto.EmployeeName))
            {
                query = query.Where(x => x.EmployeeName.Contains(dto.EmployeeName));
            }

            if (!string.IsNullOrWhiteSpace(dto.EducationBackground))
            {
                query = query.Where(x => x.EducationBackground == dto.EducationBackground);
            }

            if (dto.Status.HasValue)
            {
                query = query.Where(x => x.Status == dto.Status.Value);
            }

            // 获取总记录数
            var totalCount = await query.CountAsync();

            // 应用排序
            query = query.OrderBy(x => x.EmployeeCode);

            // 应用分页
            int pageSize = dto.PageSize > 0 ? dto.PageSize : 10;
            int pageIndex = dto.PageIndex > 0 ? dto.PageIndex : 1;
            var list = await query.Skip((pageIndex - 1) * pageSize)
                                 .Take(pageSize)
                                 .ToListAsync();

            // 返回结果
            return Json(new
            {
                code = 0,
                msg = "success",
                count = totalCount,
                data = list
            });
        }
    }
}
